﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication;

/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
    private SocketServer _socketServer;
    private bool _isApplicationRunning = false;

    public MainWindow()
    {
        InitializeComponent();
        _socketServer = new SocketServer();

        // 注册事件处理程序
        _socketServer.MessageLogged += OnMessageLogged;
        _socketServer.ServerStarted += OnServerStarted;
        _socketServer.ServerStopped += OnServerStopped;
        _socketServer.ClientConnected += OnClientConnected;
        _socketServer.ClientDisconnected += OnClientDisconnected;
    }

    private async void StartButton_Click(object sender, RoutedEventArgs e)
    {
        if (!int.TryParse(PortTextBox.Text, out int port))
        {
            LogMessage("无效的端口号。请输入有效的数字。");
            return;
        }

        // 更新 UI
        StartButton.IsEnabled = false;
        StopButton.IsEnabled = true;
        SendButton.IsEnabled = true;
        PortTextBox.IsEnabled = false;
        ConnectButton.IsEnabled = false; // 初始状态下禁用，等有客户端连接时启用

        // 启动服务器
        await _socketServer.StartAsync(port);
    }

    private void StopButton_Click(object sender, RoutedEventArgs e)
    {
        StopServer();
    }

    private void StopServer()
    {
        _socketServer.Stop();
    }

    private async void SendButton_Click(object sender, RoutedEventArgs e)
    {
        string message = MessageTextBox.Text;
        if (string.IsNullOrEmpty(message))
        {
            return;
        }

        try
        {
            await _socketServer.BroadcastMessageAsync(message);
            MessageTextBox.Clear();
        }
        catch (Exception ex)
        {
            LogMessage($"发送消息时出错: {ex.Message}");
        }
    }

    // 开始按钮事件处理
    private void BeginButton_Click(object sender, RoutedEventArgs e) { }

    // 多路阀复位按钮事件处理
    private async void ValveReset_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        ValveResetButton.IsEnabled = false;
        LogMessage("正在发送多路阀复位命令...");

        try
        {
            // 发送多路阀复位命令（cmdType = 0x01）
            bool result = await _socketServer.SendControlCommand(0x01);

            if (result)
            {
                LogMessage("多路阀复位命令发送成功，阀门正在复位中...");

                // 等待2秒后查询复位状态
                await Task.Delay(2000);

                // 查询多路阀复位状态
                var statusResult = await _socketServer.SendReadCommandAsync(0x05);
                if (statusResult.Success && statusResult.Value != null)
                {
                    bool isReset = (bool)statusResult.Value;
                    LogMessage(
                        $"多路阀复位状态: {(isReset ? "已完成复位" : "复位失败或正在进行中")}"
                    );
                }
            }
            else
            {
                LogMessage("多路阀复位命令发送失败");
            }
        }
        catch (Exception ex)
        {
            LogMessage($"执行多路阀复位时出错: {ex.Message}");
        }
        finally
        {
            ValveResetButton.IsEnabled = true;
        }
    }

    // 多路阀转动按钮事件处理
    private async void ValveRotate_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        // 验证输入
        if (
            !int.TryParse(ValvePositionTextBox.Text, out int position)
            || position < 0
            || position > 65535
        )
        {
            LogMessage("请输入有效的位置值（0-65535）");
            return;
        }

        ValveRotateButton.IsEnabled = false;
        LogMessage($"正在发送多路阀转动命令，目标位置: {position}...");

        try
        {
            // 发送多路阀转动命令（cmdType = 0x02）
            bool result = await _socketServer.SendControlCommand(0x02, position);

            if (result)
            {
                LogMessage($"多路阀转动命令发送成功，正在转动到位置 {position}...");

                // 等待3秒后查询当前位置
                await Task.Delay(3000);

                // 查询多路阀当前位置
                var positionResult = await _socketServer.SendReadCommandAsync(0x01);
                if (positionResult.Success && positionResult.Value != null)
                {
                    int currentPosition = (int)positionResult.Value;
                    if (currentPosition == position)
                    {
                        LogMessage($"多路阀已成功转动到位置 {currentPosition}");
                    }
                    else
                    {
                        LogMessage(
                            $"多路阀当前位置: {currentPosition}，目标位置: {position}，可能仍在转动中"
                        );
                    }
                }
            }
            else
            {
                LogMessage("多路阀转动命令发送失败");
            }
        }
        catch (Exception ex)
        {
            LogMessage($"执行多路阀转动时出错: {ex.Message}");
        }
        finally
        {
            ValveRotateButton.IsEnabled = true;
        }
    }

    // 打开上液电磁阀按钮事件处理
    private async void OpenValve_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        OpenValveButton.IsEnabled = false;
        LogMessage("正在发送打开上液电磁阀命令...");

        try
        {
            // 发送电磁阀控制命令（cmdType = 0x04，value = 1表示打开）
            bool result = await _socketServer.SendControlCommand(0x04, 1);

            if (result)
            {
                LogMessage("上液电磁阀已打开");
            }
            else
            {
                LogMessage("打开上液电磁阀命令发送失败");
            }
        }
        catch (Exception ex)
        {
            LogMessage($"打开上液电磁阀时出错: {ex.Message}");
        }
        finally
        {
            OpenValveButton.IsEnabled = true;
        }
    }

    // 关闭上液电磁阀按钮事件处理
    private async void CloseValve_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        CloseValveButton.IsEnabled = false;
        LogMessage("正在发送关闭上液电磁阀命令...");

        try
        {
            // 发送电磁阀控制命令（cmdType = 0x04，value = 0表示关闭）
            bool result = await _socketServer.SendControlCommand(0x04, 0);

            if (result)
            {
                LogMessage("上液电磁阀已关闭");
            }
            else
            {
                LogMessage("关闭上液电磁阀命令发送失败");
            }
        }
        catch (Exception ex)
        {
            LogMessage($"关闭上液电磁阀时出错: {ex.Message}");
        }
        finally
        {
            CloseValveButton.IsEnabled = true;
        }
    }

    // 打开气泵按钮事件处理
    private async void OpenPump_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        OpenPumpButton.IsEnabled = false;
        LogMessage("正在发送打开气泵命令...");

        try
        {
            // 发送气泵控制命令（cmdType = 0x05，value = 1表示打开）
            bool result = await _socketServer.SendControlCommand(0x05, 1);

            if (result)
            {
                LogMessage("气泵已打开");
            }
            else
            {
                LogMessage("打开气泵命令发送失败");
            }
        }
        catch (Exception ex)
        {
            LogMessage($"打开气泵时出错: {ex.Message}");
        }
        finally
        {
            OpenPumpButton.IsEnabled = true;
        }
    }

    // 关闭气泵按钮事件处理
    private async void ClosePump_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        ClosePumpButton.IsEnabled = false;
        LogMessage("正在发送关闭气泵命令...");

        try
        {
            // 发送气泵控制命令（cmdType = 0x05，value = 0表示关闭）
            bool result = await _socketServer.SendControlCommand(0x05, 0);

            if (result)
            {
                LogMessage("气泵已关闭");
            }
            else
            {
                LogMessage("关闭气泵命令发送失败");
            }
        }
        catch (Exception ex)
        {
            LogMessage($"关闭气泵时出错: {ex.Message}");
        }
        finally
        {
            ClosePumpButton.IsEnabled = true;
        }
    }

    private async void BeginApplication()
    {
        // 检查服务器是否运行
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        _isApplicationRunning = true;

        LogMessage("应用程序已开始运行");

        // 尝试发送联机命令
        LogMessage("尝试与客户端建立联机...");
        bool connectionResult = await TryConnect();

        if (connectionResult)
        {
            LogMessage("联机成功，可以开始通信");
            // TODO: 这里可以添加联机成功后的其他业务逻辑
        }
        else
        {
            LogMessage("联机失败，请检查客户端连接和通信协议");
            // 如果联机失败，可以考虑是否要自动停止应用程序
            // StopApplication();
        }
    }

    private void StopApplication()
    {
        _isApplicationRunning = false;

        LogMessage("应用程序已停止");

        // TODO: 在此处添加停止应用程序业务逻辑的代码
    }

    // 尝试连接客户端
    private async Task<bool> TryConnect(int maxAttempts = 3)
    {
        for (int attempt = 1; attempt <= maxAttempts; attempt++)
        {
            LogMessage($"联机尝试 {attempt}/{maxAttempts}...");

            bool result = await _socketServer.SendConnectionCommandAsync();
            if (result)
            {
                return true;
            }

            // 如果不是最后一次尝试，则等待一段时间后再试
            if (attempt < maxAttempts)
            {
                await Task.Delay(1000); // 等待1秒后再次尝试
            }
        }

        return false;
    }

    // 添加一个单独的联机按钮事件处理
    private async void ConnectButton_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        ConnectButton.IsEnabled = false;

        try
        {
            LogMessage("尝试与客户端建立联机...");
            bool result = await TryConnect();

            if (result)
            {
                LogMessage("联机成功，可以开始通信");
            }
            else
            {
                LogMessage("联机失败，请检查客户端连接和通信协议");
            }
        }
        finally
        {
            ConnectButton.IsEnabled = true;
        }
    }

    // 测试命令重发机制按钮事件处理
    private async void TestRetryButton_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        //TestRetryButton.IsEnabled = false;
        try
        {
            LogMessage("开始测试命令重发机制...");
            await TestRetryMechanism();
        }
        finally
        {
            //TestRetryButton.IsEnabled = true;
        }
    }

    // 测试命令重发机制
    private async Task TestRetryMechanism()
    {
        // 发送一个预期不会得到正确响应的命令，触发重发机制
        // 使用一个不太可能匹配的响应验证函数
        byte[] testCommand = new byte[] { 0x55, 0xAA, 0xFF, 0xFF, 0x00, 0x00 };

        LogMessage("发送测试命令（预期会触发重发）...");

        // 设置短超时和多次重试
        bool result = await _socketServer.SendCommandAsync(
            testCommand,
            "重发测试命令",
            (byte3, byte4) => byte3 == 0xAA && byte4 == 0xAA, // 故意设置一个不太可能匹配的条件
            0, // 客户端索引
            2000, // 短超时时间，便于快速触发重试
            5 // 最大重试次数
        );

        if (result)
        {
            LogMessage("命令执行意外成功（收到了匹配的响应）");
        }
        else
        {
            LogMessage("命令执行失败（预期行为）- 应该已经看到重试过程的日志");
        }
    }

    // 客户端连接/断开事件处理
    private void OnClientConnected(string ip, string port)
    {
        Dispatcher.Invoke(() =>
        {
            ConnectButton.IsEnabled = true;
            //TestRetryButton.IsEnabled = true;
        });
    }

    private void OnClientDisconnected(string ip, string port)
    {
        // 如果没有客户端连接，禁用联机按钮
        Dispatcher.Invoke(() => {
            // 这里可以根据实际情况检查是否还有其他客户端连接
            // 如果没有，则禁用联机按钮
            // 这个例子中简单处理，没有判断客户端数量
        });
    }

    // SocketServer 事件处理
    private void OnServerStarted()
    {
        // 服务器已启动，UI 已在 StartButton_Click 中更新
    }

    private void OnServerStopped()
    {
        Dispatcher.Invoke(() =>
        {
            StartButton.IsEnabled = true;
            StopButton.IsEnabled = false;
            SendButton.IsEnabled = false;
            PortTextBox.IsEnabled = true;
            ConnectButton.IsEnabled = false;
            //TestMultiCommandButton.IsEnabled = true;
            //TestRetryButton.IsEnabled = false;
        });
    }

    private void OnMessageLogged(string message)
    {
        LogMessage(message);
    }

    private void LogMessage(string message)
    {
        Dispatcher.Invoke(() =>
        {
            LogTextBox.AppendText(
                $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}{Environment.NewLine}"
            );
            LogTextBox.ScrollToEnd();
        });
    }

    protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
    {
        StopServer();
        if (_isApplicationRunning)
        {
            StopApplication();
        }
        base.OnClosing(e);
    }

    // 读取多路阀位置按钮事件处理
    private async void ReadValvePosition_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        LogMessage("正在读取多路阀位置...");
        ReadValvePositionButton.IsEnabled = false;

        try
        {
            var result = await _socketServer.SendReadCommandAsync(0x01);

            if (result.Success && result.Value != null)
            {
                int position = (int)result.Value;
                LogMessage($"多路阀当前位置: {position}");
            }
            else
            {
                LogMessage($"读取多路阀位置失败: {result.ErrorMessage}");
            }
        }
        catch (Exception ex)
        {
            LogMessage($"读取多路阀位置时出错: {ex.Message}");
        }
        finally
        {
            ReadValvePositionButton.IsEnabled = true;
        }
    }

    // 读取温度按钮事件处理
    private async void ReadTemperatures_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        LogMessage("正在读取各部件温度...");
        ReadTemperaturesButton.IsEnabled = false;

        try
        {
            var result = await _socketServer.SendReadCommandAsync(0x02);

            if (result.Success && result.Value != null)
            {
                var temperatures = result.Value as Dictionary<string, int>;
                if (temperatures != null)
                {
                    LogMessage("各部件温度:");
                    LogMessage($"- 蜡缸温度: {temperatures["wax_temp"]}°C");
                    LogMessage($"- 反应缸温度: {temperatures["reactor_temp"]}°C");
                    LogMessage($"- 接头温度: {temperatures["joint_temp"]}°C");
                    LogMessage($"- 多路阀温度: {temperatures["valve_temp"]}°C");
                }
                else
                {
                    LogMessage("读取温度数据格式错误");
                }
            }
            else
            {
                LogMessage($"读取温度失败: {result.ErrorMessage}");
            }
        }
        catch (Exception ex)
        {
            LogMessage($"读取温度时出错: {ex.Message}");
        }
        finally
        {
            ReadTemperaturesButton.IsEnabled = true;
        }
    }

    // 读取气压按钮事件处理
    private async void ReadPressure_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        LogMessage("正在读取气压值...");
        ReadPressureButton.IsEnabled = false;

        try
        {
            var result = await _socketServer.SendReadCommandAsync(0x03);

            if (result.Success && result.Value != null)
            {
                int pressure = (int)result.Value;
                LogMessage($"当前气压值: {pressure} Pa");
            }
            else
            {
                LogMessage($"读取气压值失败: {result.ErrorMessage}");
            }
        }
        catch (Exception ex)
        {
            LogMessage($"读取气压值时出错: {ex.Message}");
        }
        finally
        {
            ReadPressureButton.IsEnabled = true;
        }
    }

    // 读取液位信号按钮事件处理
    private async void ReadLevelSignals_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        LogMessage("正在读取液位信号...");
        ReadLevelSignalsButton.IsEnabled = false;

        try
        {
            var result = await _socketServer.SendReadCommandAsync(0x04);

            if (result.Success && result.Value != null)
            {
                var signals = result.Value as Dictionary<string, bool>;
                if (signals != null)
                {
                    LogMessage("液位信号状态:");
                    LogMessage($"- 第一液位: {(signals["level1"] ? "有液体" : "无液体")}");
                    LogMessage($"- 第二液位: {(signals["level2"] ? "有液体" : "无液体")}");
                    LogMessage($"- 第三液位: {(signals["level3"] ? "有液体" : "无液体")}");
                    LogMessage($"- 第四液位: {(signals["level4"] ? "有液体" : "无液体")}");
                }
                else
                {
                    LogMessage("读取液位信号数据格式错误");
                }
            }
            else
            {
                LogMessage($"读取液位信号失败: {result.ErrorMessage}");
            }
        }
        catch (Exception ex)
        {
            LogMessage($"读取液位信号时出错: {ex.Message}");
        }
        finally
        {
            ReadLevelSignalsButton.IsEnabled = true;
        }
    }

    // 查询多路阀复位按钮事件处理
    private async void ReadValveReset_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        LogMessage("正在查询多路阀复位状态...");
        ReadValveResetButton.IsEnabled = false;

        try
        {
            var result = await _socketServer.SendReadCommandAsync(0x05);

            if (result.Success && result.Value != null)
            {
                bool isReset = (bool)result.Value;
                LogMessage($"多路阀复位状态: {(isReset ? "已复位" : "未复位")}");
            }
            else
            {
                LogMessage($"查询多路阀复位失败: {result.ErrorMessage}");
            }
        }
        catch (Exception ex)
        {
            LogMessage($"查询多路阀复位时出错: {ex.Message}");
        }
        finally
        {
            ReadValveResetButton.IsEnabled = true;
        }
    }

    // 查询加热信号按钮事件处理
    private async void ReadHeatingSignals_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        LogMessage("正在查询加热信号...");
        ReadHeatingSignalsButton.IsEnabled = false;

        try
        {
            var result = await _socketServer.SendReadCommandAsync(0x06);

            if (result.Success && result.Value != null)
            {
                var signals = result.Value as Dictionary<string, bool>;
                if (signals != null)
                {
                    LogMessage("加热信号状态:");
                    LogMessage($"- 蜡缸右侧加热: {(signals["wax_right"] ? "开启" : "关闭")}");
                    LogMessage($"- 分配阀加热: {(signals["valve"] ? "开启" : "关闭")}");
                    LogMessage($"- 反应缸加热: {(signals["reactor"] ? "开启" : "关闭")}");
                    LogMessage($"- 蜡缸左侧加热: {(signals["wax_left"] ? "开启" : "关闭")}");
                }
                else
                {
                    LogMessage("读取加热信号数据格式错误");
                }
            }
            else
            {
                LogMessage($"查询加热信号失败: {result.ErrorMessage}");
            }
        }
        catch (Exception ex)
        {
            LogMessage($"查询加热信号时出错: {ex.Message}");
        }
        finally
        {
            ReadHeatingSignalsButton.IsEnabled = true;
        }
    }

    // 查询反应缸盖开关信号按钮事件处理
    private async void ReadReactorCover_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        LogMessage("正在查询反应缸盖开关信号...");
        ReadReactorCoverButton.IsEnabled = false;

        try
        {
            var result = await _socketServer.SendReadCommandAsync(0x07);

            if (result.Success && result.Value != null)
            {
                var signals = result.Value as Dictionary<string, bool>;
                if (signals != null)
                {
                    LogMessage("反应缸盖开关状态:");
                    LogMessage($"- 开盖把手左: {(signals["handle_left"] ? "打开" : "关闭")}");
                    LogMessage($"- 开盖把手右: {(signals["handle_right"] ? "打开" : "关闭")}");
                }
                else
                {
                    LogMessage("读取反应缸盖信号数据格式错误");
                }
            }
            else
            {
                LogMessage($"查询反应缸盖开关信号失败: {result.ErrorMessage}");
            }
        }
        catch (Exception ex)
        {
            LogMessage($"查询反应缸盖开关信号时出错: {ex.Message}");
        }
        finally
        {
            ReadReactorCoverButton.IsEnabled = true;
        }
    }

    // 开机初始化参数按钮事件处理
    private async void InitParams_Click(object sender, RoutedEventArgs e)
    {
        if (!_socketServer.IsRunning)
        {
            LogMessage("请先启动服务器！");
            return;
        }

        LogMessage("正在发送开机初始化参数...");
        InitParamsButton.IsEnabled = false;

        try
        {
            // 设置默认参数值，这些值可以根据需求进行更改或者通过界面输入
            int yeluREST = 1; // 多路阀复位值
            int yeluRestSpeed = 1; // 多路阀复位速度
            int yeluWorkSpeed = 1; // 多路阀工作速度
            int presCoef = 1; // 压力矫正系数

            // 发送初始化参数命令
            bool result = await _socketServer.SendInitParamsCommand(
                yeluREST,
                yeluRestSpeed,
                yeluWorkSpeed,
                presCoef
            );

            if (result)
            {
                LogMessage("开机初始化参数设置成功！");
                LogMessage($"- 多路阀复位值: {yeluREST}");
                LogMessage($"- 多路阀复位速度: {yeluRestSpeed}");
                LogMessage($"- 多路阀工作速度: {yeluWorkSpeed}");
                LogMessage($"- 压力矫正系数: {presCoef}");
            }
            else
            {
                LogMessage("开机初始化参数设置失败！");
            }
        }
        catch (Exception ex)
        {
            LogMessage($"设置开机初始化参数时出错: {ex.Message}");
        }
        finally
        {
            InitParamsButton.IsEnabled = true;
        }
    }

    private async void StartTestButton_Click(object sender, RoutedEventArgs e)
    {
        bool result = await _socketServer.SendConnectionCommandAsync();
        bool result2 = await _socketServer.SendControlCommand(0x01);
        //查询多路阀复位状态
        bool result3 = await WaitForstatusResultAsync();
        //多路阀转动
        // 发送多路阀转动命令（cmdType = 0x02）
        bool result4 = await _socketServer.SendControlCommand(0x02, 510);
        bool result5 = await WaitForPositionResultAsync(510);

        // 进液
        bool result6 = await _socketServer.SendControlCommand(0x04, 1);
        await Task.Delay(1000);
        // 发送气泵控制命令（cmdType = 0x05，value = 1表示打开）
        bool result7 = await _socketServer.SendControlCommand(0x05, 1);
        //液位
        var result8 = await WaitForwaterResultAsync(1);

        //转动
        bool result9 = await _socketServer.SendControlCommand(0x02, 510);
        bool result10 = await WaitForPositionResultAsync(510);

        //脱水杠温度
        bool result11 = await _socketServer.SendControlCommand(0x06, 30);

        //倒计时结束,转到普通孔位
        //转动
        bool result12 = await _socketServer.SendControlCommand(0x02, 510);
        bool result13 = await WaitForPositionResultAsync(510);

        //排液
        bool result14 = await _socketServer.SendControlCommand(0x04, 0);
        await Task.Delay(1000);
        // 发送气泵控制命令（cmdType = 0x05，value = 1表示打开）
        bool result15 = await _socketServer.SendControlCommand(0x05, 1);

        //等待液位1传感器没有信号后，再次等待60S（时间参数在界面上可调整），发送指令关闭气泵，再次等待60S（时间参数在界面上可调整），目的为了沥液进行第二次
        //排液，发送指定打开气泵，发送指令关闭排液电磁阀。
        bool result16 = await WaitForwaterResultAsync(0);
        await Task.Delay(6000);
        bool result117 = await _socketServer.SendControlCommand(0x05, 0);
        await Task.Delay(6000);
        // 发送气泵控制命令（cmdType = 0x05，value = 1表示打开）
        bool result118 = await _socketServer.SendControlCommand(0x05, 1);

        //排液
        bool result119 = await _socketServer.SendControlCommand(0x04, 0);
    }

    private async Task<bool> WaitForwaterResultAsync(int slice)
    {
        bool result = false;

        while (!result)
        {
            var tempResult = await _socketServer.SendReadCommandAsync(0x04);
            var signals = tempResult.Value as Dictionary<string, bool>;

            if (
                (slice == 1 && signals["level1"])
                || (slice == 2 && signals["level4"])
                || (slice == 0 && signals["level1"])
            )
            {
                return true;
            }
            await Task.Delay(500);
        }

        return result;
    }

    /// <summary>
    /// 等待位置
    /// </summary>
    /// <param name="position"></param>
    /// <returns></returns>
    private async Task<bool> WaitForPositionResultAsync(int position)
    {
        bool result = false;

        while (!result)
        {
            var tempResult = await _socketServer.SendReadCommandAsync(0x01);

            if (
                (position + 10 > ((int)tempResult.Value)) && (position - 10 < (int)tempResult.Value)
            )
            {
                return true;
            }
            await Task.Delay(500);
        }

        return result;
    }

    /// <summary>
    /// 等待复位
    /// </summary>
    /// <returns></returns>
    private async Task<bool> WaitForstatusResultAsync()
    {
        bool result = false;

        while (!result)
        {
            var tempResult = await _socketServer.SendReadCommandAsync(0x05);

            result = (bool)tempResult.Value;
            await Task.Delay(500);
        }

        return result;
    }
}
